package com.kzd.gtboon.main.game

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kzd.gtboon.R
import com.kzd.gtboon.custom.setTransitionStatusE
import com.kzd.gtboon.databinding.FragmentGameRankingBinding
import com.kzd.gtboon.entity.ClassifyTab
import com.kzd.gtboon.entity.GameBean
import com.kzd.gtboon.jetpack.vm.GameViewModel
import com.kzd.gtboon.main.game.adapter.Game1Adapter
import com.kzd.gtboon.main.toGameDetailsActivity
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadImage
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel

class GameRankingFragment : OwnerViewBindingFragment<FragmentGameRankingBinding>() {

    companion object {
        private const val KEY_RANKING_TYPE = "KEY_RANKING_TYPE"
        fun newInstance(type: Int): GameRankingFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(KEY_RANKING_TYPE, type)
            }
            return GameRankingFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mType: Int
        get() = arguments?.getInt(KEY_RANKING_TYPE) ?: 0

    private val mGame1Adapter: Game1Adapter<GameBean> by lazy {
        val type = when (mType) {
            1 -> Game1Adapter.Type.GAME_LIST_RANKING_1
            2 -> Game1Adapter.Type.GAME_LIST_RANKING_2
            else -> Game1Adapter.Type.GAME_LIST_RANKING_0
        }
        Game1Adapter(type)
    }

    private val mViewModel: GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> FragmentGameRankingBinding
        get() = FragmentGameRankingBinding::inflate

    override fun initView() {

        mViewBinding.includeAppRefresh.rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mGame1Adapter

        mViewBinding.tabGameRankingKind.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                mViewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate((tab?.tag ?: "0").toString())
                )
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        })

        mViewBinding.includeAppRefresh.mSmartRefreshLayout.setOnRefreshListener {
            val classify = mViewModel.gameClassifyLiveData.value?.data?.data

            if (classify.isNullOrEmpty()) {
                mViewModel.gameClassify()
                return@setOnRefreshListener
            }
            val update = mViewModel.selectedClassifyIdLiveData.value
            if (update == null) {
                mViewBinding.includeAppRefresh.mSmartRefreshLayout.finishRefresh()
            } else {
                mViewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate(update.type)
                )
            }
        }
        mViewBinding.includeAppRefresh.mSmartRefreshLayout.setOnLoadMoreListener {
            val update = mViewModel.selectedClassifyIdLiveData.value
            if (update == null) {
                mViewBinding.includeAppRefresh.mSmartRefreshLayout.finishLoadMore()
            } else {
                mViewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate(update.type, isLoadMore = true)
                )
            }
        }
    }

    override fun initData() {
        mViewModel.gameClassify()
    }

    override fun initViewMode() {

        mViewModel.gameClassifyLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response, mGame1Adapter, mViewBinding.includeAppRefresh.mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
            if (data.isNullOrEmpty())
                return@observe
            fillDataTab(data)
        })

        mViewModel.gameRankingLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response,mGame1Adapter,mViewBinding.includeAppRefresh.mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            val data = response.data?.data
                ?: return@observe
            if (isLoadMore) {
                mGame1Adapter.addData(data)
                return@observe
            }
            if (mType == 0 && data.size >= 3) {
                mGame1Adapter.type = Game1Adapter.Type.GAME_LIST_RANKING_0
                val games = data.take(3)
                mGame1Adapter.setHeaderView(
                    createViewRankingTitle(games[0], games[1], games[2])
                )
                data.removeAll(games)
            } else if (mType == 0 && data.size < 3) {
                mGame1Adapter.removeAllHeaderView()
                mGame1Adapter.type = Game1Adapter.Type.GAME_LIST_RANKING_1
            }
            mGame1Adapter.setNewInstance(data)
        })

        mViewModel.selectedClassifyIdLiveData.observe(viewLifecycleOwner, { update ->
            mViewModel.gameRanking(mType.toString(), update.type, update.isLoadMore)
        })
    }

    private fun fillDataTab(classifyTab: MutableList<ClassifyTab>) = mViewBinding.tabGameRankingKind.apply {
        for (item in classifyTab) addTab(newTab().apply {
            val view: View = LayoutInflater.from(requireContext())
                .inflate(R.layout.item_game_ranking_label, null)
            view.findViewById<TextView>(R.id.tvGameRankingLabelName)
                .text = item.name
            customView = view
            tag = item.id
        })
        visibility = View.VISIBLE
    }

    private fun createViewRankingTitle(
        gameList1: GameBean, gameList2: GameBean, gameList3: GameBean
    ): View {
        val view = LayoutInflater.from(requireContext())
            .inflate(R.layout.include_ranking_title, null)
        view.findViewById<ImageView>(R.id.ivGameRankingNo1Icon)
            .loadImage(
                src = gameList1.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<ImageView>(R.id.ivGameRankingNo2Icon)
            .loadImage(
                src = gameList2.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<ImageView>(R.id.ivGameRankingNo3Icon)
            .loadImage(
                src = gameList3.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<TextView>(R.id.tvGameRankingNo1Name)
            .text = gameList1.name
        view.findViewById<TextView>(R.id.tvGameRankingNo2Name)
            .text = gameList2.name
        view.findViewById<TextView>(R.id.tvGameRankingNo3Name)
            .text = gameList3.name
        view.findViewById<TextView>(R.id.tvGameRankingNo1Type)
            .text = gameList1.type
        view.findViewById<TextView>(R.id.tvGameRankingNo2Type)
            .text = gameList2.type
        view.findViewById<TextView>(R.id.tvGameRankingNo3Type)
            .text = gameList3.type
        view.findViewById<ConstraintLayout>(R.id.constraintLayout1)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList1.id ?: return@setOnClickListener)
            }
        view.findViewById<ConstraintLayout>(R.id.constraintLayout2)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList2.id ?: return@setOnClickListener)
            }
        view.findViewById<ConstraintLayout>(R.id.constraintLayout3)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList3.id ?: return@setOnClickListener)
            }


        view.findViewById<LinearLayout>(R.id.linearLayout1)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList1.id ?: return@setOnClickListener)
            }
        view.findViewById<LinearLayout>(R.id.linearLayout2)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList2.id ?: return@setOnClickListener)
            }
        view.findViewById<LinearLayout>(R.id.linearLayout3)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList3.id ?: return@setOnClickListener)
            }
        return view
    }


}